package io.renren.modules.sp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sp.dto.SpTeamDTO;
import io.renren.modules.sp.dto.SpTeamUserDTO;
import io.renren.modules.sp.dto.TAreaDTO;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.excel.SpTeamExcel;
import io.renren.modules.sp.service.*;
import io.renren.modules.sp.service.impl.TAreaServiceImpl;
import io.renren.modules.sys.dto.ParamDto;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
* 领队
*
* @author Mark sunlightcs@gmail.com
* @since 3.0 2023-04-20
*/
@RestController
@RequestMapping("sp/spteam")
@Api(tags="领队")
public class SpTeamController{
    @Autowired
    private SpTeamService spTeamService;
    @Autowired
    private SpTeamUserService spTeamUserService;
    @Autowired
    private TAreaService tAreaService;
    @Autowired
    private SpMatchService spMatchService;
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SpUserService spUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("sp:spteam:page")
    public Result<PageData<Map>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        /**
         * 1. 如果超级管理员查询全部
         * 2. 如果是赛事管理员，查询赛事下的代表队
         * 3. 如果是赛项管理员，查询赛项下的代表队
         */
        //获取当前登录用户
        UserDetail user = (UserDetail) SecurityUtils.getSubject().getPrincipal();
        PageData<Map> page = null;
        String userType = sysUserService.getSysUserType();
        // 9学会管理员
        if(user.getSuperAdmin()==1 || "9".equals(userType)){
            //超级管理员
            page = spTeamService.pageQuery(params);
        }else if("1".equals(userType) || "3".equals(userType) || "4".equals(userType)){
            //赛事管理员
            Map map = new HashMap();
            map.put("adminId", user.getId());
            List<SpMatchEntity> list = spMatchService.queryPageByAdmin(map);
            String sql = "(";
            String p = "";
            String c = "";
            for(int i=0; i<list.size(); i++){
                SpMatchEntity spMatchEntity = list.get(i);
                p = spMatchEntity.getProvince();
                c = spMatchEntity.getCity();
                if(i>0){
                    sql += " or ";
                }
                sql += "(";
                if(StringUtils.isNotEmpty(p)){
                    if(!"-1".equals(p)){
                        if("650000".equals(p)){
                            sql += " t.province in ('650000','660000')";
                        }else {
                            sql += " t.province = '" + p + "' ";
                        }
                    }
                }
                if(StringUtils.isNotEmpty(c)){
                    if(!"-1".equals(c)){
                        sql += " and t.city = '"+c+"' ";
                    }
                }
                sql += ") ";
            }
            sql += ")";
            if(list.size()>0){
                params.put("sql", sql);
            }
            page = spTeamService.pageQuery(params);
        } else if ("2".equals(userType)) {
            //赛项管理员角色：也可以显示代表队列表
            String sql = " t.id in ("
                    + " SELECT mit.team_id from sp_match_item_team mit"
                    + " left join sp_match_item mi on mit.match_item_id = mi.id"
                    + " where mi.admin_id = " + user.getId()
                    + " )";
            params.put("sql", sql);
            page = spTeamService.pageQuery(params);
        }

        //循环page，取省市信息
        for (Map spTeamDTO : page.getList()) {
            // 获取市
            List<ParamDto> list2 = tAreaService.queryByCode((String) spTeamDTO.get("city"));
            if (list2!=null&&list2.size()>0){
                ParamDto paramDto = list2.get(0);
                spTeamDTO.put("cityName", paramDto.getName());
            }
        }
        return new Result<PageData<Map>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    //@RequiresPermissions("sp:spteam:info")
    public Result<Map<String,Object>> get(@PathVariable("id") Long id){
        Map<String,Object> data = spTeamService.queryById(id);

        return new Result<Map<String,Object>>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sp:spteam:save")
    public Result save(@RequestBody SpTeamDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        // 根据手机号查询
        List<SpUserEntity> list = spUserService.queryList(
                new QueryWrapper<SpUserEntity>()
                        .eq("phone", dto.getPhone())
        );
        SpUserEntity user = null;
        if(list!=null && list.size()>0){
            user = list.get(0);
        }else{
            // 创建用户
            user = new SpUserEntity();
            user.setAccount(dto.getPhone());
            user.setPhone(dto.getPhone());
            user.setRealName(dto.getLeader());
            user.setRoleId("0");
            spUserService.insert(user);
            //return new Result().error("负责人手机号不存在，请先在用户模块添加");
        }

        dto.setLeaderId(user.getId());
        dto.setLeader(user.getRealName());
        dto.setCreator(user.getId());
        if(StringUtils.isNotEmpty(dto.getProvince())){
            dto.setProvince(dto.getProvince());
        }else{
            dto.setProvince("370000");
        }
        if (StringUtils.isNotEmpty(dto.getCity())){
            dto.setCity(dto.getCity());
        }else{
            dto.setCity("370200");
        }
        spTeamService.save(dto);

        SpTeamUserDTO spTeamUserDTO = new SpTeamUserDTO();
        spTeamUserDTO.setTeamId(dto.getId());
        spTeamUserDTO.setUserId(user.getId());
        spTeamUserDTO.setPhone(user.getPhone());
        // 1-领队
        spTeamUserDTO.setType(1);
        spTeamUserService.save(spTeamUserDTO);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sp:spteam:update")
    public Result update(@RequestBody SpTeamDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        spTeamService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sp:spteam:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        spTeamService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("sp:spteam:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<SpTeamDTO> list = spTeamService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "领队", list, SpTeamExcel.class);
    }


    /**
     * 启用/禁用
     * @param
     * @return
     */
    @PostMapping("updStatus")
    @ApiOperation("启用/禁用")
    @LogOperation("启用/禁用")
    public Result<SpTeamDTO> updStatus(@RequestBody SpTeamDTO dto){
        SpTeamEntity spTeamEntity = new SpTeamEntity();
        spTeamEntity.setId(dto.getId());
        spTeamEntity.setStatus(dto.getStatus());
        spTeamService.updateById(spTeamEntity);
        return new Result<SpTeamDTO>();
    }

}
